# Created by 黄景涛
# DATE: 2024/11/13

import requests

from config import settings
from org_manager import search_users_from_org

cfg = settings.cfg
headers = settings.headers
fk = settings.fk


class Role:
    """ 角色 """

    put_role_users_url = cfg.get('itsm').get('itsm_base_url') + cfg.get("itsm").get("put_role_users_route", None)
    get_role_users_url = cfg.get('itsm').get('itsm_base_url') + cfg.get("itsm").get("get_role_users_route", None)
    session = requests.session()

    def __init__(self, role_id=None, role_key=None, role_name=None):
        self.id = role_id
        self.key = role_key
        self.name = role_name
        self.full_put_role_url = self.put_role_users_url + f'/{self.id}/'

    def get_role_info(self):
        """ 获取角色的当前信息 """
        params = {
            "role_type": "GENERAL",
            "page": 1,
            "page_size": 10,
            "name__icontains": self.name
        }
        try:
            resp = self.session.get(self.get_role_users_url, params=params, headers=headers)
        except Exception as e:
            raise Exception(f'角色查询接口{self.get_role_users_url}访问失败， >>{str(e)}')

        if resp.status_code == 200 and resp.json()['data']['count'] != 0:
            members: str = resp.json()['data']['items'][0]['members']
            print(f'角色【{self.name}】信息查询成功, 原成员如下：{members.split(",")}')
            return members
        else:
            raise Exception(f'角色【{self.name}】查询失败')

    def add_member(self, members: list[str]):
        """ 添加成员 """

        members = members if isinstance(members, list) else [members]

        # 查询已有成员
        existing_members: list = self.get_role_info().split(',')

        additional_members: list = [m.strip() for m in members]
        # 追加成员
        existing_members.extend(additional_members)

        data = {
            "id": self.id,
            "role_key": self.key,
            "members": ','.join(existing_members),  # "admin,xuhua"
            "name": self.name,
            "role_type": "GENERAL",
            "tag": "",
            "relation_dict_id": 0,
            "classify_id": 0,
            "owners": "admin"
        }

        try:
            resp = self.session.put(self.full_put_role_url, data=data, headers=headers)
        except Exception as e:
            raise Exception(f'角色接口{self.full_put_role_url}访问失败， >>{str(e)}')

        if resp.status_code == 200 and resp.json().get("code", None) == 'OK':
            print(f'角色【{self.name}】添加成员完成, 现成员如下：{existing_members}')
        else:
            raise Exception(f'角色{self.name}添加成员失败')


if __name__ == '__main__':
    # 获取组织下所有成员
    org_id = 3
    members = search_users_from_org(org_id)
    member_usernames = list(map(lambda item: item[-1].strip(), members))

    # 获取itsm的角色
    role_info = {
        "role_id": 11,
        "role_key": "VIP_GROUP",
        "role_name": "VIP用户组"
    }
    role = Role(**role_info)
    # 添加成员
    role.add_member(member_usernames)
